Skip to main content

Matrix 矩阵

Action - Matrix 矩阵

matrix 可以让我们通过参数化的方式,批量地执行或编排流程。GitHub Actions 会将 matrix 中的每个参数排列组合,产生一个新的运行实例。

示例1

on: push
jobs:
node:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-16.04, ubuntu-18.04]
node: [6, 8, 10]
steps:
- uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node }}
- run: node --version

上面的 workflow 执行时, 会执行 6 个 job,以下是action后台实际执行的 workflow 示例:

>>> node ubuntu-16.04 6
>>> node ubuntu-16.04 8
>>> node ubuntu-16.04 10

>>> node ubuntu-18.04 6
>>> node ubuntu-18.04 8
>>> node ubuntu-18.04 10

无论是用来测试兼容性, 还是批量执行 Job, 都是非常好的。

示例2

jobs:
build:
strategy:
matrix:
# 指定node版本 矩阵指定多版本
node-version: [12.x, 14.x, 15.x]
# 指定os
os: ['ubuntu-latest', 'windows-latest', 'macos-latest']
# 用变量的形式,自动分配
runs-on: ${{ matrix.os }}

# 用变量的形式,自动分配
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}

#有些任务是不能在其他环境运行的
# 比如GabrielBB/xvfb-action@v1 只能在linux 下使用
# 用if条件判断一下就好
- name: Run headless unit test
if: matrix.os == 'ubuntu-latest'
uses: GabrielBB/xvfb-action@v1
with:
run: |
yarn test
yarn e2e

# node 后续任务